package cn.edu.stu.syllabus.utils;

import android.content.Context;
import android.support.annotation.IntDef;
import android.widget.Toast;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

import cn.edu.stu.syllabus.application.SyllabusApplication;
import es.dmoral.toasty.Toasty;

/**
 * Created by daidaijie on 2017/4/9.
 * 封装的Toast弹出管理类
 */

public class ToastUtils {

    private Toast mToast;

    private String lastText;

    private int lastToastType;

    private ToastUtils() {
        mToast = null;
        lastText = "";
        lastToastType = -1;
    }

    // 显示Toast
    public void showToast(@ToastTypeDef int toastType, String text, int duraction) {

        /**
         * 如果Toast的内容和类型与之前未完全消失的Toast对象一致，则只修改时间
         * 否则取消之前的Toast并进行当前的Toast显示
         */
        if (mToast != null && toastType == lastToastType && text.equals(lastText)) {
            mToast.setDuration(duraction);
        } else {
            cancelToast();
            Context context = SyllabusApplication.getContext();

            if (toastType == ToastType.SUCCESS) {
                mToast = Toasty.success(context, text, duraction);
            } else if (toastType == ToastType.INFO) {
                mToast = Toasty.info(context, text, duraction);
            } else if (toastType == ToastType.WARNING) {
                mToast = Toasty.warning(context, text, duraction);
            } else if (toastType == ToastType.ERROR) {
                mToast = Toasty.error(context, text, duraction);
            } else if (toastType == ToastType.NORMAL) {
                mToast = Toasty.normal(context, text, duraction);
            }
        }

        lastText = text;
        lastToastType = toastType;

        mToast.show();
    }


    private static final class ToastUtilsHolder {
        private static ToastUtils sToastUtils = new ToastUtils();
    }

    public static ToastUtils getInstance() {
        return ToastUtilsHolder.sToastUtils;
    }

    public void cancelToast() {
        if (mToast != null) {
            mToast.cancel();
        }
    }

    /**
     * Toast的类型
     */
    public static class ToastType {
        public static final int SUCCESS = 0;
        public static final int INFO = 1;
        public static final int WARNING = 2;
        public static final int ERROR = 3;
        public static final int NORMAL = 4;
    }

    @IntDef({ToastType.SUCCESS,
            ToastType.INFO,
            ToastType.WARNING,
            ToastType.ERROR,
            ToastType.NORMAL})
    @Retention(value = RetentionPolicy.SOURCE)
    public @interface ToastTypeDef {
    }

}
